#!/usr/bin/perl

$hostPrefix = $ARGV[0];
@location = ($ARGV[1], $ARGV[2]);

$maxX = $ARGV[3];
$maxY = $ARGV[4];

$localHostName = $hostPrefix."_".$location[0]."_".$location[1];
$port = 10000 + $location[0] * $maxY + $location[1];

print "Launching AddressTable\n";
system("nohup /usr/share/cassandra/bin/cassandra");
sleep(4);

print "Configuring AddressTable\n";
system("/usr/share/cassandra/bin/cassandra-cli -h $localHostName -p 9160 < atht.txt");

print "Loading Hosts\n";
open(HOSTS, ">", "hosts.txt");
print HOSTS "use AddressTable;\n";
for($x = 1; $x < $maxX + 1; $x++) {
    for($y = 1; $y < $maxY + 1; $y++) {
        $port = 10000 + ($x * ($maxY)) + $y;
        print HOSTS "set hosts[long($x$y)][utf8(id)] = long($x$y);\n";
        print HOSTS "set hosts[long($x$y)][utf8(location_id)] = long($x$y);\n";
        print HOSTS "set hosts[long($x$y)][utf8(host)] = utf8($hostPrefix"."_".$x."_"."$y);\n";
        print HOSTS "set hosts[long($x$y)][utf8(port)] = long($port);\n";
        print HOSTS "set locations[long($x$y)][utf8(id)] = long($x$y);\n";
        print HOSTS "set locations[long($x$y)][utf8(x)] = long($x);\n";
        print HOSTS "set locations[long($x$y)][utf8(y)] = long($y);\n";
        print HOSTS "set host_locations[utf8($hostPrefix"."_".$x."_"."$y)][utf8(location_id)] = long($x$y);";

    }
}
close(HOSTS);
system("/usr/share/cassandra/bin/cassandra-cli -h $localHostName -p 9160 < hosts.txt");

print "Launching primary ".$localHostName." at location ".$location[0].", ".$location[1]."\n";

$ENV{'CASSANDRA_CONF'}="/usr/share/ariadne/$localHostName/conf";
system("nohup /usr/share/cassandra/bin/cassandra -p /var/run/$localHostName.pid");
sleep(4);

$port = 10000 + $location[0] * $maxY + $location[1];
print "Configuring Primary\n";
system("/usr/share/cassandra/bin/cassandra-cli -h $localHostName -p $port < kvkkv.txt");

